package com.sky.aspect;

import com.alibaba.fastjson.JSONObject;
import com.sky.anno.CleanCache;
import com.sky.enumeration.DataType;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Map;

@Component
@Aspect//通知类
@Slf4j

public class CleanCacheAspect {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 功能描述:  定义切入点 TODO
     *
     * @return : void
     */
    @Pointcut("@annotation(com.sky.anno.CleanCache)")
    public void cleanCachePointCut() {
    }

    @Before("cleanCachePointCut()")
    public void cleanCache(JoinPoint joinPoint) {
        //1.获取操作类型,数据类型
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        //获取方法上的注解
        CleanCache cleanCache = method.getAnnotation(CleanCache.class);
        //获取注解上的属性值
        DataType dataType = cleanCache.dataType();
        Object arg = joinPoint.getArgs()[0];
        OperationType operationType = cleanCache.opType();
        Long categoryId = null;
        //判断操作是增删改
        if (operationType == OperationType.DELETE) {
            //删除操作
            //判断是对菜品套餐,分类

        } else {
            //增改操作
            //判断是对菜品套餐,分类
            String jsonString = JSONObject.toJSONString(arg);
            Map map = JSONObject.parseObject(jsonString, Map.class);
            if (dataType == DataType.CATEGORY) {
                redisTemplate.delete("home_category");
                return;
            }
            categoryId = Long.valueOf(map.get("categoryId").toString());
            if (dataType == DataType.DISH) {
                redisTemplate.delete("DISH_" + categoryId);
                return;
            }
            if (dataType == DataType.SETMEAL) {
                redisTemplate.delete("SETMEAL_" + categoryId);
                return;
            }
        }
    }
}
